#include "c3_main.h"
#include "uart.h"

#include "driver/uart.h"

static const char *TAG = "uart: ";
/*********     串口  *******/
#define ECHO_TEST_TXD GPIO_NUM_7
#define ECHO_TEST_RXD GPIO_NUM_6
#define ECHO_TEST_RTS (UART_PIN_NO_CHANGE)
#define ECHO_TEST_CTS (UART_PIN_NO_CHANGE)
#define ECHO_UART_PORT_NUM UART_NUM_1
#define ECHO_UART_BAUD_RATE 115200
#define ECHO_TASK_STACK_SIZE (CONFIG_EXAMPLE_TASK_STACK_SIZE)
#define BUF_SIZE (16)
/*********     串口  *******/

void uart_init()
{
    /* 配置UART驱动参数,
     * 通讯引脚并安装驱动程序 */
    uart_config_t uart_config = {
        .baud_rate = ECHO_UART_BAUD_RATE,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_DEFAULT,
    };
    int intr_alloc_flags = 0;

#if CONFIG_UART_ISR_IN_IRAM
    intr_alloc_flags = ESP_INTR_FLAG_IRAM;
#endif

    ESP_ERROR_CHECK(uart_driver_install(ECHO_UART_PORT_NUM, BUF_SIZE * 2, 0, 0, NULL, intr_alloc_flags));
    ESP_ERROR_CHECK(uart_param_config(ECHO_UART_PORT_NUM, &uart_config));
    ESP_ERROR_CHECK(uart_set_pin(ECHO_UART_PORT_NUM, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS));
}

void uart_jie_shou(void* str)
{
    // 为传入数据配置临时缓冲区
    uint8_t *data = (uint8_t *) malloc(BUF_SIZE);
    size_t xBytesSent;
    const TickType_t x100ms = pdMS_TO_TICKS(50);

    while (1)
    {
        // 从UART读取数据
        int len = uart_read_bytes(ECHO_UART_PORT_NUM, data, (BUF_SIZE - 1), 50 / portTICK_PERIOD_MS);
        // 将数据写回UART
        /*
        uart_write_bytes(ECHO_UART_PORT_NUM, (const char *) data, len);
        if (len) {
            data[len] = '\0';
            ESP_LOGI(TAG, "Recv str: %s", (char *) data);
        }
        */
        if (len > 0)
        {
            data[len] = '\0';
            ESP_LOGI(TAG, "Recv str: %s", (char *)data);
            //xBytesSent = xMessageBufferSend(zhuanFanP, (void *)data, len, x100ms);
            // xBytesSent = xMessageBufferSend(zhuanFanP, (void *)data, strlen(data), x100ms);
        }
        // uart_write_bytes(ECHO_UART_PORT_NUM, (const char *) data, len);
        vTaskDelay(200 / portTICK_PERIOD_MS);
    }
}